import React, { useState, useRef } from 'react';
import { Form, Input, Button, Steps, message } from 'antd';
import { MailOutlined, LockOutlined, SafetyOutlined, MobileOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import Vcode from 'react-vcode';
import './ForgotPassword.scss';

interface ResetPasswordForm {
  account: string;
  code: string;
  captcha: string;
  newPassword: string;
  confirmPassword: string;
}

const ForgotPassword: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm<ResetPasswordForm>();
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [accountType, setAccountType] = useState<'email' | 'phone'>('email');
  const [captchaCode, setCaptchaCode] = useState('');
  const [countdown, setCountdown] = useState(0);
  const vcodeRef = useRef<any>(null);

  // 验证账号
  const handleVerifyAccount = async () => {
    try {
      await form.validateFields(['account', 'captcha']);
      
      const account = form.getFieldValue('account');
      const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(account);
      const isPhone = /^1[3-9]\d{9}$/.test(account);
      
      if (!isEmail && !isPhone) {
        message.error('请输入正确的邮箱或手机号');
        return;
      }
      
      setAccountType(isEmail ? 'email' : 'phone');
      
      // TODO: 调用验证账号接口
      message.success('验证码已发送');
      setCurrentStep(1);
    } catch (error) {
      console.error('验证失败', error);
    }
  };

  // 验证验证码
  const handleVerifyCode = async () => {
    try {
      await form.validateFields(['code']);
      
      // TODO: 调用验证码验证接口
      setCurrentStep(2);
    } catch (error) {
      console.error('验证失败', error);
    }
  };

  // 重置密码
  const handleResetPassword = async (values: ResetPasswordForm) => {
    setLoading(true);
    try {
      // TODO: 调用重置密码接口
      
      setTimeout(() => {
        message.success('密码重置成功，请使用新密码登录');
        navigate('/login');
      }, 1000);
    } catch (error) {
      message.error('密码重置失败');
    } finally {
      setLoading(false);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    const account = form.getFieldValue('account');
    if (!account) {
      message.error(`请输入${accountType === 'email' ? '邮箱' : '手机号'}`);
      return;
    }

    // TODO: 调用发送验证码接口
    message.success('验证码已发送');
    
    // 倒计时
    let count = 60;
    setCountdown(count);
    const timer = setInterval(() => {
      count--;
      setCountdown(count);
      if (count === 0) {
        clearInterval(timer);
      }
    }, 1000);
  };

  // 刷新图片验证码
  const handleRefreshCaptcha = () => {
    if (vcodeRef.current) {
      vcodeRef.current.onClick();
    }
  };

  // 验证码改变
  const handleCaptchaChange = (code: string) => {
    setCaptchaCode(code);
  };

  const steps = [
    { title: '验证账号' },
    { title: '验证身份' },
    { title: '重置密码' },
  ];

  return (
    <div className="forgot-password-container">
      <div className="forgot-password-background">
        <div className="bg-overlay"></div>
      </div>
      
      <div className="forgot-password-content">
        <div className="forgot-password-card">
          <div className="forgot-password-header">
            <h1>找回密码</h1>
            <p>重置您的账号密码</p>
          </div>

          <Steps current={currentStep} items={steps} className="reset-steps" />

          <div className="form-container">
            <Form
              form={form}
              name="forgot-password"
              onFinish={handleResetPassword}
              autoComplete="off"
              size="large"
            >
              {/* 步骤1: 验证账号 */}
              {currentStep === 0 && (
                <>
                  <Form.Item
                    name="account"
                    rules={[
                      { required: true, message: '请输入邮箱或手机号' },
                    ]}
                  >
                    <Input
                      prefix={<MailOutlined />}
                      placeholder="请输入邮箱或手机号"
                    />
                  </Form.Item>

                  <Form.Item
                    name="captcha"
                    rules={[
                      { required: true, message: '请输入验证码' },
                      { len: 4, message: '验证码为4位' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || value.toLowerCase() === captchaCode.toLowerCase()) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('验证码错误'));
                        },
                      }),
                    ]}
                  >
                    <div className="captcha-input-wrapper">
                      <Input
                        prefix={<SafetyOutlined />}
                        placeholder="请输入验证码"
                        maxLength={4}
                      />
                      <div className="vcode-wrapper">
                        <Vcode
                          ref={vcodeRef}
                          onChange={handleCaptchaChange}
                          width={120}
                          height={40}
                          length={4}
                        />
                        <Button
                          icon={<ReloadOutlined />}
                          onClick={handleRefreshCaptcha}
                          className="refresh-btn"
                          size="small"
                          title="刷新验证码"
                        />
                      </div>
                    </div>
                  </Form.Item>

                  <Button
                    type="primary"
                    onClick={handleVerifyAccount}
                    block
                    size="large"
                  >
                    下一步
                  </Button>
                </>
              )}

              {/* 步骤2: 验证身份 */}
              {currentStep === 1 && (
                <>
                  <div className="step-info">
                    <p>
                      验证码已发送至 {accountType === 'email' ? '邮箱' : '手机'}：
                      <span className="account-mask">
                        {form.getFieldValue('account')}
                      </span>
                    </p>
                  </div>

                  <Form.Item
                    name="code"
                    rules={[
                      { required: true, message: '请输入验证码' },
                      { len: 6, message: '验证码为6位数字' }
                    ]}
                  >
                    <div className="code-input-wrapper">
                      <Input
                        prefix={accountType === 'email' ? <MailOutlined /> : <MobileOutlined />}
                        placeholder="请输入6位验证码"
                        maxLength={6}
                      />
                      <Button
                        onClick={handleSendCode}
                        disabled={countdown > 0}
                      >
                        {countdown > 0 ? `${countdown}秒后重试` : '重新发送'}
                      </Button>
                    </div>
                  </Form.Item>

                  <div className="step-actions">
                    <Button onClick={() => setCurrentStep(0)}>
                      上一步
                    </Button>
                    <Button
                      type="primary"
                      onClick={handleVerifyCode}
                    >
                      下一步
                    </Button>
                  </div>
                </>
              )}

              {/* 步骤3: 重置密码 */}
              {currentStep === 2 && (
                <>
                  <Form.Item
                    name="newPassword"
                    rules={[
                      { required: true, message: '请输入新密码' },
                      { min: 6, max: 20, message: '密码长度为6-20个字符' },
                      { 
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
                        message: '密码必须包含大小写字母和数字' 
                      }
                    ]}
                  >
                    <Input.Password
                      prefix={<LockOutlined />}
                      placeholder="请输入新密码（6-20个字符）"
                    />
                  </Form.Item>

                  <Form.Item
                    name="confirmPassword"
                    dependencies={['newPassword']}
                    rules={[
                      { required: true, message: '请确认新密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('newPassword') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                      }),
                    ]}
                  >
                    <Input.Password
                      prefix={<LockOutlined />}
                      placeholder="请再次输入新密码"
                    />
                  </Form.Item>

                  <div className="password-tips">
                    <p>密码要求：</p>
                    <ul>
                      <li>长度为6-20个字符</li>
                      <li>必须包含大写字母</li>
                      <li>必须包含小写字母</li>
                      <li>必须包含数字</li>
                    </ul>
                  </div>

                  <div className="step-actions">
                    <Button onClick={() => setCurrentStep(1)}>
                      上一步
                    </Button>
                    <Button
                      type="primary"
                      htmlType="submit"
                      loading={loading}
                    >
                      完成重置
                    </Button>
                  </div>
                </>
              )}
            </Form>
          </div>

          <div className="forgot-password-footer">
            <Link to="/login" className="back-link">
              返回登录
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ForgotPassword;

